package org.ww.search.service.impl;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.ww.common.to.es.SkuEsModel;
import org.ww.search.config.ElasticSearchConfig;
import org.ww.search.constant.EsConstant;
import org.ww.search.service.ProductSaveService;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: gmall
 * @description: 商品保存service
 * @author: ww
 * @create: 2024-02-19 15:07
 **/
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        //BulkRequest bulkRebuest, RequestOptions options

        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            String skuEsModelJsonString = JSON.toJSONString(skuEsModel);
            indexRequest.source(skuEsModelJsonString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);

        //TODO:如果批量错误进行处理
        boolean b = bulk.hasFailures();
        List<String> skuIds = Arrays.stream(bulk.getItems()).map(item -> item.getId()).collect(Collectors.toList());

        log.info("商品上架完成:{}",skuIds);

        return b;

    }
}
